package cool.tianyou.blue.bird.activity;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Build;
import android.os.Bundle;
import android.widget.BaseAdapter;
import android.widget.ListView;

import cool.tianyou.blue.bird.constant.Constant;
import cool.tianyou.blue.bird.R;
import cool.tianyou.blue.bird.dialog.LoadingDialog;
import cool.tianyou.blue.bird.model.Device;
import cool.tianyou.blue.bird.model.vo.DeviceMessage;
import cool.tianyou.blue.bird.service.MQTTMessageCallBack;
import cool.tianyou.blue.bird.util.HttpUtil;
import cool.tianyou.blue.bird.util.JSONUtil;
import cool.tianyou.blue.bird.util.SpUtil;

import java.util.ArrayList;
import java.util.List;

public class DeviceActivity extends AppCompatActivity implements MQTTMessageCallBack {
    private final List<Device> devices = new ArrayList<>();
    private BaseAdapter deviceAdapter;
    private LoadingDialog loadingDialog;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device);
        loadingDialog = new LoadingDialog(DeviceActivity.this, "正在加载...").showDialog();
        ListView deviceList = findViewById(R.id.device_list);
        init();
        deviceAdapter = new DeviceListAdapter(devices, this);
        deviceList.setAdapter(deviceAdapter);
//        if ( != null) {
//            MQTTService.instance.addIGetMessageCallBack(this);
//        }
        Constant.USER_INFO.TOKEN = SpUtil.getString(this, Constant.SP_CONSTANT.TOKEN, "");
        Constant.USER_INFO.USER_ID = SpUtil.getString(this, Constant.SP_CONSTANT.USER_ID, "");
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void init() {
        //获取列表数据
        HttpUtil.get(this, null, "/device", apiResult -> {
            List<Device> devices = JSONUtil.parseArray(apiResult.getData(), Device.class);
            DeviceActivity.this.devices.clear();
            DeviceActivity.this.devices.addAll(devices);
            runOnUiThread(() -> {
                deviceAdapter.notifyDataSetChanged();
                loadingDialog.dismiss();
            });
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void setMessage(DeviceMessage message) {
        init();
    }
}

